from flask import Blueprint, request, jsonify
import random, json
from db import db1
from werkzeug.security import generate_password_hash, check_password_hash

from rediscon import r

bp_user = Blueprint("user", __name__)


# 发送验证码接口
@bp_user.route('/smscode')
def smscode():
    # 获取手机号
    mobile = request.args.get('mobile')
    # 生成验证码
    code = str(random.randint(1000, 9999))
    # 把验证码存入redis
    r.set_str(mobile, code, 60)
    # 返回结果
    return jsonify({"code": 200, 'scode': code})


@bp_user.route('/userM', methods=['POST'])
def userM():
    # 获取用户输入
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    # 验证码验证 1.去redis中取验证码 2对比
    code = r.get_str(data['mobile'])
    # 查看验证码是否过期
    if not code:
        return jsonify({"code": 10010, 'mes': '验证码已经过期，请重新发送'})
    if code != data['code']:
        return jsonify({"code": 10011, 'mes': '验证码输入错误'})
    # 手机号唯一验证
    sql = "select id from user where mobile='%s'" % (data['mobile'])
    res = db1.find(sql)
    if res:
        return jsonify({"code": 10012, 'mes': '手机号已经存在，不能再次注册'})
    # 注册，写入用户表
    sql = "insert into user values(0,'%s','%s')" % (data['mobile'], generate_password_hash(data['password']))
    db1.insert(sql)
    # 返回结果
    return jsonify({"code": 200})


# 登录
@bp_user.route('/login', methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    # 根据手机号查询
    sql = "select * from user where mobile='%s'" % (data['mobile'])
    res = db1.find(sql)
    # 假如存在比对密码
    if res:
        if check_password_hash(res['password'], data['password']):
            # 密码正确返回id,mobile
            return jsonify({'code': 200, 'id': res['id'], 'mobile': res['mobile']})
        else:
            return jsonify({'code': 10016, 'mes': '密码错误'})
    else:
        return jsonify({'code': 10017, 'mes': '用户不存在'})


# 降序展示
@bp_user.route('/userlist')
def userlist():
    sql = "select * from user order by id desc"
    res = db1.findall(sql)
    return jsonify({"code": 200, 'list': res})